package com.fw.core;

import java.util.List;

import com.fw.config.Constants;
import com.fw.config.Handlers;
import com.fw.config.Interceptors;
import com.fw.config.FwConfig;
import com.fw.config.Plugins;
import com.fw.config.Routes;
import com.fw.log.Logger;
import com.fw.plugin.IPlugin;

public class Config {

	private static final Constants constants = new Constants();
	private static final Routes routes = new Routes() {
		public void config() {}
	};
	private static final Plugins plugins = new Plugins();
	private static final Interceptors interceptors = new Interceptors();
	private static final Handlers handlers = new Handlers();
	private static Logger logger;

	private Config() {
	}

	static void configFw(FwConfig fwConfig) {
		fwConfig.configConstant(constants);
		initLoggerFactory();
		fwConfig.configRoute(routes);
		fwConfig.configPlugin(plugins);
		startPlugins();
		fwConfig.configInterceptor(interceptors);
		fwConfig.configHandler(handlers);
	}

	public static final Constants getConstants() {
		return constants;
	}

	public static final Routes getRoutes() {
		return routes;
	}

	public static final Plugins getPlugins() {
		return plugins;
	}

	public static final Interceptors getInterceptors() {
		return interceptors;
	}

	public static Handlers getHandlers() {
		return handlers;
	}

	private static void startPlugins() {
		List<IPlugin> pluginList = plugins.getPluginList();
		if (pluginList != null) {
			for (IPlugin plugin : pluginList) {
				try {
					boolean success = plugin.start();
					if (!success) {
						String message = "Plugin start error: " + plugin.getClass().getName();
						logger.error(message);
						throw new RuntimeException(message);
					}
				} catch (Exception e) {
					String message = "Plugin start error: " + plugin.getClass().getName() + ". \n" + e.getMessage();
					logger.error(message, e);
					throw new RuntimeException(message, e);
				}
			}
		}
	}

	private static void initLoggerFactory() {
		Logger.init();
		logger = Logger.getLogger(Config.class);
		FwFilter.initLogger();
	}
}
